package dao

import (
	"encoding/json"
	"fmt"
	"gin_maker_chat/model"

	"github.com/gomodule/redigo/redis"
)

var (
	MyUserDao *UserDao
)

type UserDao struct {
	pool *redis.Pool
}

// 使用工厂模式，创建UserDao实例
func NewUserDao(pool *redis.Pool) (userDao *UserDao) {
	userDao = &UserDao{
		pool: pool,
	}
	return
}

//根据用户账号获取User实例

func (this *UserDao) getUserByUserName(conn redis.Conn, userName string) (user *model.User, err error) {

	res, err := redis.String(conn.Do("HGET", "users", userName))
	fmt.Println("从redis中获取用户信息，res=", res)
	if err != nil {
		if err == redis.ErrNil {
			err = model.ERROR_USER_NOT_EXISTS
		}
		return
	}
	user = &model.User{}
	err = json.Unmarshal([]byte(res), user)
	if err != nil {
		fmt.Println("获取用户信息，json.Unmarshal,err=", err)
		return
	}
	return
}

// 登录验证
func (this *UserDao) UserLogin(userName, passWord string) (user *model.User, err error) {
	//从连接池中取出一根链接
	conn := this.pool.Get()
	defer conn.Close()
	user, err = this.getUserByUserName(conn, userName)
	if err != nil {

		return
	}
	if user.PassWord != passWord {
		err = model.ERROR_USER_PWD
		return
	}
	return
}

// 注册验证
func (this *UserDao) UserRegister(user *model.User) (err error) {
	//从连接池中取出一根链接
	conn := this.pool.Get()
	defer conn.Close()
	_, err = this.getUserByUserName(conn, user.UserName)
	if err == nil {
		//不报错说明用户已经存在
		err = model.ERROR_USER_EXISTS
		fmt.Println("注册的用户已经存在")
		return
	}
	//执行到这，需要将用户保存到redis
	data, err := json.Marshal(user)
	if err != nil {
		fmt.Println("注册用户序列化，err=", err)
		return
	}
	_, err = conn.Do("HSet", "users", user.UserName, string(data))

	if err != nil {
		fmt.Println("保存注册的用户信息失败，err=", err)
		return
	}
	return
}
